from datetime import datetime

from app import db


class Food(db.Model):
    __tablename__ = 'foods'

    # 表的字段
    food_id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    name = db.Column(db.String(255), nullable=False)
    category_id = db.Column(db.Integer, nullable=False)
    category_1 = db.Column(db.String(255))
    category_2 = db.Column(db.String(255))
    category = db.Column(db.String(255))
    evaluation = db.Column(db.Float)
    calories = db.Column(db.Float)
    carbohydrate = db.Column(db.Float)
    fat = db.Column(db.Float)
    protein = db.Column(db.Float)
    fiber = db.Column(db.Float)
    vitamin_a = db.Column(db.Float)
    vitamin_c = db.Column(db.Float)
    vitamin_e = db.Column(db.Float)
    carotene = db.Column(db.Float)
    thiamine = db.Column(db.Float)
    riboflavin = db.Column(db.Float)
    niacin = db.Column(db.Float)
    cholesterol = db.Column(db.Float)
    magnesium = db.Column(db.Float)
    calcium = db.Column(db.Float)
    iron = db.Column(db.Float)
    zinc = db.Column(db.Float)
    copper = db.Column(db.Float)
    manganese = db.Column(db.Float)
    potassium = db.Column(db.Float)
    phosphorus = db.Column(db.Float)
    sodium = db.Column(db.Float)
    selenium = db.Column(db.Float)
    measurement_unit = db.Column(db.String(50))
    related_foods = db.Column(db.Text)
    image_url = db.Column(db.String(255))
    img_name = db.Column(db.String(255))
    aliases = db.Column(db.Text)
    price = db.Column(db.Float, nullable=False)
    stock_quantity = db.Column(db.Integer, default=0)
    description = db.Column(db.Text)
    is_available = db.Column(db.Integer, default=1)
    created_at = db.Column(db.DateTime, default=datetime.utcnow)
    updated_at = db.Column(db.DateTime, onupdate=datetime.utcnow)

    # 与Recipe的多对多关系
    # recipes = db.relationship('Recipe', secondary='recipe_food', back_populates='foods')

    def __repr__(self):
        return f'<Food {self.name}>'

    # to_dict 方法
    def to_dict(self):
        return {
            'food_id': self.food_id,
            'name': self.name,
            'category_id': self.category_id,
            'category_1': self.category_1,
            'category_2': self.category_2,
            'calories': self.calories,
            'protein': self.protein,
            'carbohydrate': self.carbohydrate,
            'fat': self.fat,
            'img_name': self.img_name,
            'image_url': self.image_url,
            'aliases': self.aliases,
            'evaluation': self.evaluation,
            'measurement_unit': self.measurement_unit,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S')
        }